Python Interview Questions and Answers
Related differences
Ques 26. How to create a class in Python?
In Python programming, the class is created using a class keyword. The syntax for creating a class is as follows:
Example:
class ClassName:
code statement
Ques 27. What is the syntax for creating an instance of a class in Python?
The syntax for creating an instance of a class is as follows:
<object-name> = <class-name>(<arguments>)
Ques 28. Define what is “Method” in Python programming.
The Method is defined as the function associated with a particular object. The method which we define should not be unique as a class instance. Any type of object can have methods.
Ques 29. Why can't I use an assignment in an expression?
Many people used to C or Perl complain that they want to use this C idiom: while (line = readline(f)) {
...do something with line...
}
where in Python you're forced to write this:
while True:
line = f.readline() if not line:
break
...do something with line...
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:
if (x = 0) {
...error handling...
}
else {
...code that only works for nonzero x...
}
The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
Ques 30. How do you set a global variable in a function in Python?
x = 1 # make a global
def f():
print x # try to print the global
for j in range(100):
if q>3:
x=4
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently, the print x attempts to print an uninitialized local variable and will trigger a NameError.
The solution is to insert an explicit global declaration at the start of the function:
def f():
global x
print x # try to print the global
for j in range(100):
if q>3:
x=4
In this case, all references to x are interpreted as references to the x from the module namespace.
Most helpful rated by users:
- What is Python?
- How do I share global variables across modules?
- How do you set a global variable in a function in Python?
- Why can't I use an assignment in an expression?
- What are the rules for local and global variables in Python?